import type { Middleware } from '../context/types';

// 持久化中间件，用于将数据存储到localStorage
export const localStorageMiddleware: Middleware = (key, value, next) => {
  // 先调用下一个中间件
  next(value);

  // 然后将最终值存储到localStorage
  try {
    const serializedValue = JSON.stringify(value);
    localStorage.setItem(`context_${key}`, serializedValue);
  } catch (error) {
    console.error(`Failed to persist ${key} to localStorage:`, error);
  }
};

// 持久化中间件，用于将数据存储到sessionStorage
export const sessionStorageMiddleware: Middleware = (key, value, next) => {
  // 先调用下一个中间件
  next(value);

  // 然后将最终值存储到sessionStorage
  try {
    const serializedValue = JSON.stringify(value);
    sessionStorage.setItem(`context_${key}`, serializedValue);
  } catch (error) {
    console.error(`Failed to persist ${key} to sessionStorage:`, error);
  }
};

// 持久化恢复中间件，用于从存储中恢复数据
export const persistenceRecoveryMiddleware: Middleware = (key, value, next) => {
  // 尝试从localStorage恢复数据
  try {
    const serializedValue = localStorage.getItem(`context_${key}`);
    if (serializedValue !== null) {
      const restoredValue = JSON.parse(serializedValue);
      next(restoredValue);
      return;
    }
  } catch (error) {
    console.error(`Failed to restore ${key} from localStorage:`, error);
  }

  // 如果localStorage中没有，使用原始值
  next(value);
};
